package cn.liberg.coder.tool.template;

import cn.liberg.coder.tool.LibergToolContext;
import cn.liberg.coder.tool.util.FileUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class TempDBInitializer {
    public static final String NAME = "DBInitializer";

    public static void createFileIfAbsent(LibergToolContext context) {
        File file = new File(context.getDataPath() + NAME +".java");
        if(!file.exists()) {
            try(BufferedWriter bw = FileUtils.bufferedWriter(file)) {
                writeInitContent(context, bw);
                System.out.println("> " + context.getDataPackage() + "." + NAME + "  created.");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("> " + context.getDataPackage() + "." + NAME + "  already exists.");
        }
    }

    private static void writeInitContent(LibergToolContext context, BufferedWriter bw) throws IOException {
        bw.write("package "+context.getDataPackage()+";\r\n");
        bw.write("\r\n");
        bw.write("import cn.liberg.core.OperatorException;\r\n");
        bw.write("\r\n");
        bw.write("public class "+NAME+" {\r\n");
        bw.write("\r\n");
        bw.write("    public void initData() throws OperatorException {\r\n");
        bw.write("    }\r\n");
        bw.write("}\r\n");
        bw.write("\r\n");
    }
}
